package com.neuedu.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class FileUtils {
    private static String endpoint = "http://oss-cn-beijing.aliyuncs.com";
    private static String accessKeyId = "LTAI4GCH6t7C928r2NutJpuF";
    private static String accessKeySecret = "TxMIC49WmEnbVqTUkb6nwMpoA07E0B";
    private static String bucketName = "bucketmy";

    //提供单文件上传下载路径
    public static String uploadFile(MultipartFile file) throws IOException {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        PutObjectResult putObjectResult = ossClient.putObject(bucketName, file.getOriginalFilename(), file.getInputStream());
        //设置过期时间
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        //阿里云服务器的url
        String url = ossClient.generatePresignedUrl(bucketName, file.getOriginalFilename(), expiration).toString();
        return url;
    }

    //提供多文件上传下载路径，提供文件，返回下载的超链接，自己放到数据库，同上
    public static List uploadFiles(MultipartFile[] file) throws IOException {
        List urls = new ArrayList<String>();
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //设置过期时间
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 60);

        for(int i =0 ;i< file.length; i++){
            PutObjectResult putObjectResult = ossClient.putObject(bucketName, file[i].getOriginalFilename(), file[i].getInputStream());
            String url = ossClient.generatePresignedUrl(bucketName, file[i].getOriginalFilename(), expiration).toString();
            urls.add(url);
        }
        return urls;
    }

}
